package com.wva.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.wva.gateway.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 全局过滤器
 */
@Component
@Slf4j
public class AuthenticationFilter implements GlobalFilter {
    private static final String LOGIN_USER = "Login-User-Id";

    @Autowired
    JwtUtils jwtUtils;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //生成traceId
        String traceId = UUID.randomUUID().toString();
        MDC.put("traceId", traceId);

        //基本信息
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //TODO 请求头含有userId为非法请求
        if (!CollectionUtil.isEmpty(request.getHeaders().get(LOGIN_USER))) {
            response.setRawStatusCode(500);
            return response.setComplete();
        }

        //从请求头取出token
        List<String> list = request.getHeaders().get("TOKEN");
        String jwt = null;
        if (!CollectionUtil.isEmpty(list)) {
            jwt = list.get(0);
        }

        //尝试解析token
        Long userId = null;
        if (jwt != null) {
            try {
                Map<String, Object> claims = jwtUtils.parse(jwt);
                log.debug("claims:{}", claims);
                userId = Long.valueOf((Integer)(claims.get("userId")));
            } catch (Exception e) {
                log.error("登录令牌校验不通过", e);
                //TODO 解析失败，令牌错误或过期
                response.setRawStatusCode(500);
                return response.setComplete();
            }
        }

        //登录成功
        MDC.put("userId", String.valueOf(userId));

        //构造请求信息
        ServerHttpRequest.Builder mutate = request.mutate();
        mutate.header("Trace-Id", traceId);
        if (userId != null) mutate.header(LOGIN_USER, String.valueOf(userId));
        ServerHttpRequest newRequest = mutate.build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    }
}